import type { LoginUser } from '@/api/auth/types';
import { defineStore } from 'pinia';
import { useRouter } from 'vue-router';
import { guestService } from '@/services/guestService';

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref<any>('');
    const router = useRouter();
    const setToken = (value: string) => {
      token.value = value;
    };
    const clearToken = () => {
      token.value = void 0;
    };

    const userInfo = ref<LoginUser>();
    const setUserInfo = (value: LoginUser) => {
      userInfo.value = value;
    };
    const clearUserInfo = () => {
      userInfo.value = void 0;
    };

    const logout = async () => {
      // 如果需要调用接口，可以在这里调用
      clearToken();
      clearUserInfo();

      // 清除游客状态
      guestService.clearGuestStatus();

      // 清空应用数据
      const { useAppStore } = await import('./app');
      const appStore = useAppStore();
      appStore.clearAppData();

      // 重置游客登录尝试状态，允许重新进行游客登录
      const { resetGuestLoginAttempt } = await import('@/routers');
      resetGuestLoginAttempt();

      // 退出登录后，重新进行游客登录
      try {
        await guestService.autoLoginAsGuest();
      }
      catch (error) {
        console.error('退出登录后游客自动登录失败:', error);
      }

      router.replace({ name: 'chat' });
    };

    // 新增：登录弹框状态
    const isLoginDialogVisible = ref(false);

    // 新增：打开弹框方法
    const openLoginDialog = () => {
      isLoginDialogVisible.value = true;
    };

    // 新增：关闭弹框方法（可根据需求扩展）
    const closeLoginDialog = () => {
      isLoginDialogVisible.value = false;
    };

    // 检查是否为游客状态
    const isGuestMode = computed(() => {
      const result = guestService.isGuest() && !!token.value && userInfo.value?.username === 'guest';
      console.log('isGuestMode计算:', {
        isGuest: guestService.isGuest(),
        hasToken: !!token.value,
        username: userInfo.value?.username,
        result,
      });
      return result;
    });

    return {
      token,
      setToken,
      clearToken,
      userInfo,
      setUserInfo,
      clearUserInfo,
      logout,
      // 新增：暴露弹框状态和方法
      isLoginDialogVisible,
      openLoginDialog,
      closeLoginDialog,
      // 游客模式状态
      isGuestMode,
    };
  },
  {
    persist: true,
  },
);
